package org.example.erat.composite;

import org.example.erat.entity.ClassEntity;
import org.example.erat.entity.Course;
import org.example.erat.entity.Experiment;
import org.example.erat.entity.Student;
import org.example.erat.log.core.LoggerSingleton;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 统计组合组件
 * 组合多个统计组件
 */
@Component
public class StatisticsComposite implements StatisticsComponent {

    private final Map<String, StatisticsComponent> components = new HashMap<>();

    @Autowired
    private List<AbstractStatisticsComponent> componentList;

    @PostConstruct
    public void init() {
        for (AbstractStatisticsComponent component : componentList) {
            addComponent(component);
        }

        LoggerSingleton.getInstance().info("统计组合组件初始化完成，包含组件: {}",
                String.join(", ", components.keySet()));
    }

    @Override
    public Map<String, Object> execute(ClassEntity classEntity, Course course,
                                     List<Student> students, List<Experiment> experiments,
                                     Map<String, Object> reportData) {
        LoggerSingleton.getInstance().info("执行统计组合组件");

        Map<String, Object> result = new HashMap<>();

        // 执行所有子组件
        for (StatisticsComponent component : components.values()) {
            Map<String, Object> componentResult = component.execute(classEntity, course, students, experiments, reportData);
            result.putAll(componentResult);
        }

        LoggerSingleton.getInstance().info("统计组合组件执行完成");
        return result;
    }

    @Override
    public String getName() {
        return "composite";
    }

    @Override
    public void addComponent(StatisticsComponent component) {
        components.put(component.getName(), component);
    }

    @Override
    public void removeComponent(StatisticsComponent component) {
        components.remove(component.getName());
    }

    @Override
    public StatisticsComponent getComponent(String name) {
        return components.get(name);
    }
}
